//Function to remove a file.
#include<stdio.h>
#include"../include/BST.h"
//#include ""
#define ERR_VFS_REMOVEFILE_01 "CANNOT_FIND_SPECIFIED_PATH_OR_FILE"


void remove_file(char *fpath)
{
	//Get the file descriptor for given file.

		//printf("\n---------starting remove file-----------\n");
		int blockNo, file_offset=0;
		char ch,delm;
		char blank=' ';
		FILE *fp;
		if(fpath==NULL)
		{
			//printf("The file path is null.");
			return;
		}
		
		fd *searchedFile=bstSearchNode(&bstRoot,fpath);

		//printf("\nfd contents before %s\n",searchedFile->file_name);

		if(searchedFile==NULL)
		{
			printf("removefile_FAILURE %s\n",ERR_VFS_REMOVEFILE_01);
		}
		else if(searchedFile->fileType == 'D')
		{
			printf("removefile_FAILURE %s\n",ERR_VFS_REMOVEFILE_01);
		}
		else
		{
			//Get the block number from given descriptor.
			blockNo=searchedFile->blockNum;
			//printf("\nblock number=%d\n",blockNo);
				 
			//Free the block and change entry in freelist.
			fp=fopen(header.fileSystemLabel,"rb+");
				
			if(fp==NULL)
			{
				//printf("Unable to open file \n");
			} 
			else
			{
				fseek(fp,31+(blockNo*sizeof(flist)),SEEK_SET);
				fread(&ch,sizeof(char),1,fp);
				//printf("block content=%c",ch);
				
				if(ch=='1')
				{
					fseek(fp,31+(blockNo*sizeof(flist)),SEEK_SET);
					ch='0';
					fwrite(&ch,sizeof(char),1,fp);
				}
				
				fseek(fp,0,SEEK_SET);
				while(delm!='!')
				{
					fread(&delm,sizeof(delm),1,fp);
					file_offset++;
				}
				//printf("\nfile_offset==%d\n",file_offset);
				fseek(fp,(file_offset+(blockNo*1024)),SEEK_SET);
				int count=0;
				while(((ch=fgetc(fp))!=EOF)&&(count<1024))
				{	count++;
					//ch=fgetc(exfile);
					fwrite(&blank,sizeof(blank),1,fp);
				}
				//printf("\ncount=%d",count);
				
				// IF success , remove from narytree, bst and hash table.
				
				//fd *del=*searchedFile;
				fd delFile;
				strcpy(delFile.file_name,searchedFile->file_name);
				strcpy(delFile.file_name,searchedFile->path);
				
				////printf("fd contents %s",searchedFile->file_name);				
				//printtree(naryRoot);	


				bstDeleteNode(&bstRoot,fpath);				
				//printf("After BST delete");
				
				hashDelete(hash,*searchedFile);

				//printf("After hash delete");
				char *path;			
				
				path=parsePath(fpath);
				//printf("After parsePath");

				delete_node(&naryRoot,fpath);

				//printtree(naryRoot);
				printf("removefile_SUCCESS\n");
			
				
			}
		}
}
